package csx.study.demo.interceptor;


import csx.study.demo.dto.UserDTO;
import csx.study.demo.entity.User;
import csx.study.demo.utils.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 拦截器
 */
//拦截器是aop思想的一种实现，算hooks
@Component
public class LoginInterceptor implements HandlerInterceptor {

    // controller执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session
        HttpSession session = request.getSession();

        //获取用户
        Object userDTO =  session.getAttribute("user");

        //用户不存在
        if (userDTO == null) {
            response.setStatus(401);
            return false;
        }

        //非法的用户类型
        if(!(userDTO instanceof UserDTO)) {
            response.setStatus(401);
            return false;
        }

        //存到ThreadLocal
        UserHolder.saveUser((UserDTO) userDTO);

        return true;
    }

    // controller执行之后，return之后
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }

    //TODO 这一块是SpringMVC的内容，搞懂什么是视图
    //视图渲染完成时触发
    //一般用于数据销毁
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
